package com.haizhi.crm.persist.builder;

import com.google.common.collect.Maps;
import com.haizhi.crm.common.util.Getter;
import com.haizhi.crm.persist.constant.PersistTarget;
import com.haizhi.crm.persist.model.PersistReq;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by chengmo on 2018/6/19.
 */
public class PersistReqBuilder {

    private String graph;
    private String schema;
    private PersistReq request = new PersistReq();

    public PersistReqBuilder(String graph, String schema) {
        this.graph = graph;
        this.schema = schema;
        this.setGraphAndSchema();
    }

    /**
     * Gets a persist request object.
     *
     * @return
     */
    public PersistReq get() {

        return request;
    }

    public PersistReqBuilder addTargets(PersistTarget... targets) {
        request.addTargets(targets);
        return this;
    }

    public PersistReqBuilder addSource(SourceBuilder source) {
        Map<String, Object> api = request.getRequestApi();
        List<Map<String, Object>> sources = Getter.getListMap(api.get(PKeys.SOURCES_FIELD));
        if (sources == null) {
            sources = new ArrayList<>();
            api.put(PKeys.SOURCES_FIELD, sources);
        }
        Map<String, Object> sourceMap = new LinkedHashMap<>();
        sourceMap.put(PKeys.OBJECT_KEY_FIELD, source.getObjectKey());
        sourceMap.put(PKeys.SOURCE_FIELD, Maps.newHashMap(source.getSource()));
        sources.add(sourceMap);
        return this;
    }

    ///////////////////////
    // private functions
    ///////////////////////
    private void setGraphAndSchema() {
        Map<String, Object> api = request.getRequestApi();
        api.put(PKeys.GRAPH_FIELD, graph);
        api.put(PKeys.SCHEMA_FIELD, schema);
    }
}
